<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Http\Resources\AddressResource;
use App\Models\Area;
use App\Models\Address;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class AddressController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index()
    {
        /** @var User $user */
        $user=\Auth::user();
        $address=$user->address;
        return  AddressResource::collection($address);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param Address $address
     * @return AddressResource
     */
    public function store(Request $request ,Address $address)
    {
        $address->fill($request->all());
        $address->user_id=\Auth::id();
        $address->save();
        return new AddressResource($address);
    }

    /**
     * 返回创建的创建所需要的的地址数据
     * @param Area $area
     * @return mixed
     */
    public function create(Area $area)
    {
        return $area->getAreaList();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param Address $address
     * @return AddressResource
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(Request $request, Address $address)
    {
        $this->authorize('update',$address);
        //更新用户数据
        $address->update($request->except(['id']));
        return new AddressResource($address);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Address $address
     * @return \Illuminate\Http\Response
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function destroy(Address $address)
    {
        $this->authorize('update',$address);
        //更新用户数据
        $address->delete();
        return response()->setStatusCode(204);
    }
}
